package org.BooCrack.bookstore.pay.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.BooCrack.bookstore.common.pojo.BSResult;
import org.BooCrack.bookstore.common.utils.Response;
import org.BooCrack.bookstore.common.utils.ResponseResult;
import org.BooCrack.bookstore.model.entity.BookInfo;
import org.BooCrack.bookstore.model.entity.Orders;
import org.BooCrack.bookstore.model.service.IOrderDetailService;
import org.BooCrack.bookstore.model.service.IOrderService;
import org.BooCrack.bookstore.pay.Ipay;
import org.BooCrack.bookstore.pay.PayContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import javax.servlet.http.HttpServletResponse;
import java.util.List;


@RestController
//@RequestMapping("/payment")
@RequestMapping("/user/V4")
@Api(value = "v1", tags = "4.BooCrack书城支付接口")
public class PayController {

    @Autowired
    private Ipay ipay;



    @Autowired
    private IOrderService orderService;

    @Autowired
    private IOrderDetailService orderDetailService;

    @PostMapping("/payment/{orderId}")
    @ApiOperation(value = "根据id支付", notes = "根据id支付")
    public ResponseResult paymentPage(@PathVariable("orderId") String orderId, HttpServletResponse response, Model model){


        BSResult bsResult = orderService.findOrderById(orderId);
        Orders order = (Orders) bsResult.getData();

        List<BookInfo> books = orderDetailService.findBooksByOrderId(order.getOrderId());

        PayContext payContext = new PayContext();
        payContext.setResponse(response);
        payContext.setOrders(order);
        payContext.setBookInfos(books);

        try {
            //alipay.pay(payContext);
            ipay.pay(payContext);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("exception", "支付出错了!");
            //return "exception";
            return Response.createFailResp("支付出错了!");
        }
        //return "pay_success";
        return Response.createOkResp("支付成功");
    }

    @GetMapping("/payment")
    @ApiOperation(value = "查看支付", notes = "查看支付")
    public ResponseResult returnUrl(String out_trade_no,Model model){



        BSResult bsResult = orderService.findOrderById(out_trade_no);
        Orders order = (Orders) bsResult.getData();

        List<BookInfo> books = orderDetailService.findBooksByOrderId(order.getOrderId());

        PayContext payContext = new PayContext();
        payContext.setOrders(order);
        payContext.setBookInfos(books);

        orderService.updateOrderAfterPay(payContext);


        return Response.createOkResp("完成全部支付流程");
    }



}
